-- UIActivity
-- Created by chengb Aug/25/2015
-- 活动界面（本界面已废弃）

require "game/ui/form/dungeon/UIEnterDungeon"

UIActivity = class("UIActivity", function()
    return cc.Layer:create();
end);

function UIActivity.create()
    return UIActivity.new();
end

-- 页面类型
local PAGE_TYPE_MAIN = 1;    -- 主页面
local PAGE_TYPE_SUB  = 2;    -- 子页面

-- 构造函数
function UIActivity:ctor()
    self:setName("UIActivity");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/activity/Activity.csb");
    self:addChild(node);
    self.node = node;

    -- 获取今日活动列表（目前仅需要获取迷宫活动）
    local activityIds = ActivityDungeonM.getIdsByDay(dayOfWeek());
    self.activityIds = activityIds or {};

    local scrollview = findChildByName(self.node, "TOP/scrollview");
    self.scrollview = scrollview;

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 适配
    self:resize();

    -- 重绘
    self:redraw();
end

-- 适配
function UIActivity:resize()
    local w = AlignM.frameSize.width;
    local h = AlignM.frameSize.height;

    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- TOP顶部居中并缩放至合适大小
    AlignM.alignToTopCenter(node, "TOP");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");

    local scale = w / DESIGN_WIDTH;

    -- 设置scroll的新视口高度
    local scrollview = findChildByName(self.node, "TOP/scrollview");
    local scrollViewSize = scrollview:getContentSize();

    local height = (h / scale) - 400;
    scrollview:setContentSize(scrollViewSize.width, height);
end

-- 注册点击事件
function UIActivity:registerTouchEvent()
    local TOP = findChildByName(self.node, "TOP");
    local BT = findChildByName(self.node, "BT");

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(BT, "btn_back");
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");

            -- 如果是主页，则关闭界面
            if self.pageType == PAGE_TYPE_MAIN then
                UIMgr.getCurrentScene():removeFormByName("UIActivity");
            else
                -- 否则切换至主页
                self:showMainPage();
            end
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
end

-- 注册事件处理回调函数
function UIActivity:registerEventCallback()

    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIActivity 界面析构清理");
            EventMgr.removeAll("UIActivity");
        end
    end);
end

-- 重绘
function UIActivity:redraw()
    local node = self.node;

    -- 设置标题文本
    local titleLabel = findChildByName(node,"TOP/title_node/title")
    titleLabel:setString(getLocStr("activity_title"));
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 默认显示活动主页
    self:showMainPage();
end

-- 显示活动主页
function UIActivity:showMainPage()
    self.pageType = PAGE_TYPE_MAIN;

    local function initFunc(child, info)
        self:initMainItem(child, info)
    end

    -- 搜集活动信息
    local list = {};
    for _, id in pairs(self.activityIds) do
        local icon = ActivityDungeonM.query(id, ACTIVITY_GRADE_EASY, "main_icon");
        icon = "main/" .. icon;
        table.insert(list, { ["id"] = id, ["icon"] = icon, });
    end

    self:showPage(self.pageType, list, getLocStr("activity_title"), initFunc, true);
end

-- 显示活动二级子页面
function UIActivity:showSubPage(id)
    self.pageType = PAGE_TYPE_SUB;
    local scrollview = self.scrollview;
    scrollview:removeAllChildren();

    -- 收集活动信息
    local activities = ActivityDungeonM.getActivitiesById(id);
    local activityName = ActivityDungeonM.query(id, ACTIVITY_GRADE_EASY, "name");

    -- 重绘标题
    self:redrawTitle(activityName);

    local itemNode = cc.CSLoader:createNode("layout/main/SubMapItem.csb");
    local widget = replaceNodeWithWidget(itemNode);

    -- 左边距
    local leftMargin = 25;

    -- 行间距
    local gap = 15;
    local widgetHeight = 107;

    -- 活动个数
    local totalNum = #activities;

    local startHeight = 0;

    -- 计算总高度
    local totalHeight = totalNum * (widgetHeight + gap);
    if totalHeight < scrollview:getInnerContainerSize().height then
        startHeight = scrollview:getInnerContainerSize().height - totalHeight;
    end

    scrollview:setInnerContainerSize(cc.size(scrollview:getInnerContainerSize().width,
        math.max(totalHeight, scrollview:getInnerContainerSize().height)));

    self.items = {};
    local i = 0;
    for j = #activities, 1, -1 do
        local info = activities[j];
        local child = widget:clone();
        local x = leftMargin;
        local y = startHeight + i * (widgetHeight + gap);
        child:setPositionX(x);
        child:setPositionY(y);

        table.insert(self.items, child);

        -- 初始化二级页面项
        self:initSubItem(child, info)

        scrollview:addChild(child);
        i = i + 1;
    end

    -- 默认滑到最顶端
    scrollview:scrollToTop(0.1, true);

    -- 播放飞入效果
    local list = {};
    for i = #self.items, 1, -1 do
        table.insert(list, self.items[i]);
    end

    commonScrollItemFlyIn(list);
end

-- 重绘标题
function UIActivity:redrawTitle(title)
    local offset = cc.p(0, 0);

    if getLang() == "en" then
        offset = cc.p(20, 0);

        if title == "Hero" then
            offset = cc.p(12, 0);
        end
    end

    -- 设置标题文本
    local titleLabel = findChildByName(self.node, "TOP/title_node/title")
    titleLabel:setString(title);
    TextStyleM.setArtWordTitleStyle(titleLabel);
end

-- 显示活动页面
function UIActivity:showPage(pageType, list, title, itemInitFunc, showEffect)
    local scrollview = self.scrollview;

    -- 先清空所有页面
    scrollview:removeAllChildren();

    -- 标记类型
    self.pageType = pageType;

    -- 重绘标题
    self:redrawTitle(title);

    local iconNode  = cc.CSLoader:createNode("layout/activity/ActivityItem.csb");
    local widget = replaceNodeWithWidget(iconNode);

    -- 左边距
    local leftMargin = 0;

    -- 行间距
    local gap = 10;
    local offset = 0;

    -- 单个表项高度
    local widgetHeight = 145;
    if pageType ~= PAGE_TYPE_MAIN then
        widgetHeight = 110;
        gap = 0;

        offset = -3;
    end

    local totalNum = #list;

    local startHeight = 0;

    -- 计算总高度
    local totalHeight = totalNum * (widgetHeight + gap);
    if totalHeight < scrollview:getInnerContainerSize().height then
        startHeight = scrollview:getInnerContainerSize().height - totalHeight - 20;
    end

    startHeight = startHeight + offset;

    -- 设置内部滚动区域的高度
    scrollview:setInnerContainerSize(cc.size(scrollview:getInnerContainerSize().width,
        math.max(totalHeight, scrollview:getInnerContainerSize().height)));

    self.items = {};
    local i = 0;
    for j = #list, 1, -1 do
        local info = list[j];
        local child = widget:clone();
        local x = leftMargin;
        local y = startHeight + i * (widgetHeight + gap);
        child:setPositionX(x);
        child:setPositionY(y);

        -- 初始化
        itemInitFunc(child, info);

        scrollview:addChild(child);
        i = i + 1;

        table.insert(self.items, child);
    end

    -- 默认滑到最顶端
    scrollview:scrollToTop(0.1, true);

    if showEffect then
        local list = {};
        for i = #self.items, 1, -1 do
            table.insert(list, self.items[i]);
        end

        commonScrollItemFlyIn(list);
    end
end

-- 初始化主页项
function UIActivity:initMainItem(child, info)
    child.info = info;
    local bg = child:getChildByName("bg");
    bg:loadTexture(getActivityIconPath(info.icon));

    -- 显示活动标语
    self:redrawSlogans(child, info);

    -- 注册点击事件
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            bg:runAction(cc.ScaleTo:create(0.1, 0.97));
        elseif eventType == ccui.TouchEventType.canceled then
            bg:runAction(cc.ScaleTo:create(0.1, 1));
        elseif eventType == ccui.TouchEventType.ended then
            bg:runAction(cc.ScaleTo:create(0.1, 1));

            local function callFunc()
                self:showSubPage(info.id);
            end
            performWithDelay(self, callFunc, 0.1);
        end
    end
    bg:addTouchEventListener(onClick);

    -- 每隔2秒检查一下剩余时间
    local function checkRemainTime()
        local remainHour = ActivityDungeonM.getRemainTime(info.id);
        if remainHour ~= child.lastHour then
            -- 新的小时开始了，刷新一下
            self:redrawSlogans(child, info);
        end
        performWithDelay(child, checkRemainTime, 2);
    end
    performWithDelay(child, checkRemainTime, 2);
end

-- 重绘活动标语
function UIActivity:redrawSlogans(child, info)
    local bg = child:getChildByName("bg");
    local descLabel = findChildByName(bg, "desc");
    descLabel:setVisible(true);

    -- 获取活动标语
    local id = info.id;
    local slogans = ActivityDungeonM.query(id, ACTIVITY_GRADE_EASY, "slogans") ;
    local desc = "";
    if type(slogans) == "string" and slogans ~= "" then
        desc = desc .. slogans .. "\n";
    end

    if string.match(desc, "{remain_time}") ~= nil then
        -- 获取剩余倒计时
        local remainHour = ActivityDungeonM.getRemainTime(id);
        child.lastHour = remainHour;
        local timeStr = remainHour .. "h";
        desc = string.gsub(desc, "{remain_time}", timeStr);
    end

    TextStyleM.setOutlineStyle(descLabel, TextStyleM.TEXT_OUTLINE_SIZE, TextStyleM.TEXT_OUTLINE_COLOR_DARK);
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -2, 1.2);

    applyString(descLabel, desc);
end

-- 初始化二级页面项
function UIActivity:initSubItem(child, info)
    child.info = info;

    local dungeonId = info["dungeon_id"];

    -- 关卡名称
    local name = DungeonAreaM.query(dungeonId, "name");
    local nameLabel = findChildByName(child, "name");
    nameLabel:setString(name);

    -- 关卡背景图片
    local areaImg = findChildByName(child, "area_bg");
    local areaIcon = DungeonAreaM.query(dungeonId, "area_bg");
    areaImg:loadTexture(getAreaBgPath(areaIcon));

    -- 难度
    local difficulty = DungeonAreaM.query(dungeonId, "layer_fix") + 1;
    local layerLabel = findChildByName(child, "layer");
    local maxFloor = DungeonAreaM.query(dungeonId, "max_floor");
    layerLabel:setString(string.format(getLocStr("sub_area_layer"), maxFloor, difficulty));

    -- 隐藏钻石奖励图标
    local diamondImage = findChildByName(child, "diamond_bg");
    diamondImage:setVisible(false);
    local diamondNumLabel = findChildByName(child, "num");
    diamondNumLabel:setVisible(false);
    local lightImage = findChildByName(child, "light");
    lightImage:setVisible(false);

    -- 显示活动小图标
    local heroImage = findChildByName(child, "hero_icon");
    local icon = info["icon"];
    heroImage:loadTexture(getActivityIconPath(icon));
    heroImage:setVisible(true);

    -- 设置文本风格
    -- 需要将文字先放大再缩小，以解决描边不平滑的问题
    TextStyleM.setOutlineStyle(nameLabel, TextStyleM.TEXT_OUTLINE_SIZE, TextStyleM.TEXT_OUTLINE_COLOR_DARK);
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_ORANGE, true, -3, 1.2);
    TextStyleM.setOutlineStyle(layerLabel, TextStyleM.TEXT_OUTLINE_SIZE, TextStyleM.TEXT_OUTLINE_COLOR_DARK);
    TextStyleM.setTextStyle(layerLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -2, 1.2);

    -- 显示体力消耗
    local lifeNode = findChildByName(child, "life_icon");
    local requireLife = DungeonAreaM.calcDungeonLifeCost(dungeonId);
    local layer = createLifeLayer(requireLife, "right", -0.4);
    lifeNode:removeAllChildren();
    lifeNode:addChild(layer);

    local bg = findChildByName(child, "bg");

    -- 背景图片水平翻转
    bg:setFlippedX(true);

    -- 注册点击事件
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            bg:runAction(cc.ScaleTo:create(0.1, 0.97));
        elseif eventType == ccui.TouchEventType.canceled then
            bg:runAction(cc.ScaleTo:create(0.1, 1));
        elseif eventType == ccui.TouchEventType.ended then
            bg:runAction(cc.ScaleTo:create(0.1, 1));

            if ActivityDungeonM.getRemainTime(info.id) <= 0 then
                -- 活动已结束
                alert(getLocStr("activity_is_over"));
                return;
            end

            -- 如果体力不足，弹出购买提示
            local requireLife = DungeonAreaM.calcDungeonLifeCost(dungeonId);
            if ME.user.dbase:query("life", 0) < requireLife then
                confirmBuyLife();
                return;
            end

            -- 打开关卡进入界面
            UIMgr:getCurrentScene():removeFormByName("UIEnterDungeon");
            local uiEnterDungeon = UIEnterDungeon.create(dungeonId);
            UIMgr.getCurrentScene():addForm(uiEnterDungeon);
            AudioM.playFx("ui_open1");
        end
    end
    bg:addTouchEventListener(onClick);
end



